import axios from 'axios'

/**
 * 根据url获取图片base64
 * @param {string} url
 * @returns base64
 */
async function getImgBase64(url) {
    const res = await axios({
        method: 'post',
        url,
        responseType: 'blob',
    })
    if (res.data) {
        return await toBase64(res.data)
    } else {
        return ''
    }
}

function toBase64(blob) {
    return new Promise((resolve, reject) => {
        const fileReader = new FileReader()
        fileReader.onload = (e) => {
            resolve(e.target.result)
        }
        fileReader.readAsDataURL(blob)
        fileReader.onerror = () => {
            reject('')
        }
    })
}

export { getImgBase64, toBase64 }
